<?php

defined('IN_IA') or exit('Access Denied');

require_once __DIR__."/plugin/vendor/autoload.php";
class zw_printerModuleSite extends WeModuleSite
{

    private $zw_printer = 'zw_printer';

    public function doWebPrint()
    {
        global $_W,$_GPC;
        foreach ($_GPC as $k => $v){
            if($k == 'device_id'){
                if($v == ''){
                    $mes = '终端号不能为空';
                    $status = 0;
                }
            }elseif($k == 'device_secret'){
                if($v == '秘钥不能为空'){
                    $mes = '秘钥不能为空';
                    $status = 0;

                }
            }
            elseif($k == 'appid'){
                if($v == 'appid不能为空'){
                    $mes = 'appid不能为空';
                    $status = 0;

                }
            }
            elseif($k == 'appsecret'){
                if($v == ''){
                    $mes = 'appsecret必须填写';
                    $status = 0;

                }
            }else if($k == 'printdata') {
                if ($v == '') {
                    $mes = '打印内容为空';
                    $status = 0;

                }
            }
            else{
                unset($_GPC[$k]);
            }

        }
        $row = $_GPC;
        $weid = $_W['uniacid'];
        $row['weid'] = $weid;
        if(isset($status)&&$status == 0){
            $mes = "添加失败";
            include $this->template('index');
        }else{
            $app_id = $_GPC['appid'];

            $app_secret = $_GPC['appsecret'];

            $device_id = $_GPC['device_id'];

            $device_secret = $_GPC['device_secret'];

            $rpc = new \zhongwu\protocol\RpcClient($app_id, $app_secret, 'http://api.zhongwuyun.com');

            $Zprinter = new \zhongwu\Printer($rpc);


            $printdata = empty($_GPC['printdata']) ? '中午云拥有自主研发的云打印机，提供稳定高效，高可用的云打印方案' : $_GPC['printdata'];

            try {

                $ret = $Zprinter->set_args($device_id, $device_secret)->cloud_print($printdata);

            } catch (Exception $e) {

                throw new Exception($e);

            }

            $errNum = json_decode($ret,true)['errNum'];

            if($errNum == 0){
                $mes = "打印成功";
            }
        }

        echo "<script>alert('".$mes."');location.href = '/index.php?c=site&a=entry&do=printer&m=zw_printer';</script>";

    }

}